package com.moshang.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.moshang.mall.product.dao.CategoryDao;
import com.moshang.mall.product.entity.vo.Catalog2Vo;
import com.moshang.mall.product.entity.vo.Catalog3Vo;
import com.moshang.mall.product.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moshang.mall.utils.PageUtils;
import com.moshang.mall.utils.Query;

import com.moshang.mall.product.entity.CategoryEntity;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        //查出所有分类
        List<CategoryEntity> list=baseMapper.selectList(null);
        //树形结构
        List<CategoryEntity> level1Menus = list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).map((menu)->{
            menu.setChild(getChilds(menu,list));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeCateByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Cacheable({"categorys"})
    @Override
    public List<CategoryEntity> getLeve1Cate() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", "0"));
        return categoryEntities;
    }


    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDb() {
        List<CategoryEntity> leve11Cate = getLeve1Cate();
        Map<String, List<Catalog2Vo>> parent_cid = leve11Cate.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), l2.getCatId().toString(), l2.getName(), null);
                    List<CategoryEntity> catalog3VoList=baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (catalog3VoList!=null){
                        List<Catalog3Vo> collect = catalog3VoList.stream().map(l3 -> {
                            Catalog3Vo catalog3Vo = new Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(),l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());

            }
            return catalog2Vos;
        }));
        return parent_cid;
    }
    public Map<String, List<Catalog2Vo>> getCatalogJsonRedisLock() {
        String uuid= UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock){
            Map<String, List<Catalog2Vo>> catalogJsonFromDb;
            try {
          catalogJsonFromDb = getCatalogJsonFromDb();
            }finally {
                String script="IF redis.call('get',KEYS[1]) == ARGV[1] THEN RETURN redis.call('del',KEYS[1]) ELSE RETURN 0 END";
                stringRedisTemplate.execute(new DefaultRedisScript<Integer>(script, Integer.class), Collections.singletonList("lock"), uuid);
            }

//            String lockValue=redisTemplate.opsForValue().get("lock");
//            if (uuid.equals(lockValue)){
//                redisTemplate.delete("lock");
//            }
            //lua脚本

            return catalogJsonFromDb;
        }else {
            return getCatalogJsonRedisLock();
        }
    }

    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isBlank(catalogJson)){
            Map<String, List<Catalog2Vo>> catalogJsonFromDb=getCatalogJsonFromDb();
            stringRedisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(catalogJsonFromDb));
            return  catalogJsonFromDb;
        }
        Map<String, List<Catalog2Vo>> stringListMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return stringListMap;

    }
    private List<CategoryEntity> getChilds(CategoryEntity root,List<CategoryEntity> all){
      List<CategoryEntity> child = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId()).map(categoryEntity -> {
          categoryEntity.setChild(getChilds(categoryEntity, all));
          return categoryEntity;
      }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
      return child;
  }
}